#include "main.h"
int ListInitiate(LNode **head){
    LNode *l;
    l =(LNode*)malloc(sizeof(LNode));
    if(l == NULL)
    { printf("创建失败");return 1;}
    l->next = NULL;
    *head = l;
    return 0;
}

int ListLength(LNode *head) {
    LNode *move;
    int i=0;
    move = head->next;
    while (move)
    {
        i++;
        move=move->next;
    }
    return i;
}

int ListInsert(LNode *head, int i, DataType x) {
    if (i < 0 && i > ListLength(head))
        return 1;
    LNode *new, *p;
    new = (LNode *) malloc(sizeof(LNode));
    if (new == NULL) {
        printf("插入失败");
        return 1;
    }
    new->data = x;
    int j = 1;
    p = head;
    while (j < i + 1 && p->next) {
        p = p->next;
        j++;
    }
    if (j == i + 1) {
        new->next = p->next;
        p->next = new;
    } else
    {
        return 1;
    }
    return 0;
}

int ListDelete(LNode *head, int i, DataType *x) {
    LNode *p,*node;
    int j=0;
    p=head;
    while ((p->next)&&(j<i)){
        p=p->next;
        j++;
    }
    if(!(p->next)||(j>i))
        return 1;
    node=p->next;
    *x=node->data;
    p->next=node->next;
    free(node);
    return 0;
}

int ListGet(LNode *head, int i, DataType *x) {
    LNode *move;

    move = head->next;
    while (move&&i!=0)
    {
        i--;
        move=move->next;
    }
    *x=move->data;
    return 0;
}

int Destroy(LNode **head)
{   LNode *p;
    while (*head){
        p=(*head)->next;
        free(*head);
        *head=p;
    }
    if(*head!=NULL)
        return 1;
    return 0;
}

void main(void) {
    LNode *head;
    int i, x;
    ListInitiate(&head);/*初始化*/
    for (i = 0; i < 10; i++) {
        if (ListInsert(head, i, i + 1) != 0) /*插入10个数据元素*/
        {
            printf("错误! \n");
            return;
        }
    }
    if (ListDelete(head, 4, &x) != 0) { /*删除数据元素5*/
        printf("错误! \n");
        return;
    }
    for (i = 0; i < ListLength(head); i++) {
        if (ListGet(head, i, &x) != 0) /*取元素*/
        {
            printf("错误! \n");
            return;
        } else printf("%d\n", x);/*显示数据元素*/
    }
    Destroy(&head);
}
